%% ex4.m
% set dir: src/
close all;
clear; clc;

%% generate image
SZ = 512;
img = zeros(SZ, SZ);
for i=1:60
    for j=1:10
        img(226+i, 251+j) = 255;
    end
end
f = img ./ sum(img,'all');

%% generate spectrograms
F = dft2D(f);
Fc = fftshift(F);
S = log(1 + abs(Fc));

%% compute 2d fft
imh = imread("../data/house.tif");
imh2 = imread("../data/house02.tif");
imlg = imread("../data/lena_gray_512.tif");
imls = imread("../data/lunar_surface.tif");
imC = imread("../data/Characters_test_pattern.tif");

Fh = dft2D(imh(:,:,1));
Fh2 = dft2D(imh2);
Flg = dft2D(imlg);
Fls = dft2D(imls);
FC = dft2D(imC);

shiftedH = fftshift(log(abs(Fh) + 1));
shiftedH2 = fftshift(log(abs(Fh2) + 1));
shiftedLg = fftshift(log(abs(Flg) + 1));
shiftedLs = fftshift(log(abs(Fls) + 1));
shiftedC = fftshift(log(abs(FC) + 1));

%% visualize
% part 1
figure;
tiledlayout(2,2,"TileSpacing","tight");
nexttile;
imshow(f, []);
title('Original');
axis off;
nexttile;
imshow(real(F), []);
title('Spectrogram');
axis off;
nexttile;
imshow(real(Fc), []);
title('Centralized Spectrogram');
axis off;
nexttile;
imshow(S, []);
title('Logarithmic Spectrogram');
axis off;
colormap gray;
% part 2
figure;
tiledlayout(1,5,"TileSpacing","tight");
nexttile;
imshow(shiftedH, []);
title("house.tif");
axis off;
nexttile;
imshow(shiftedH2, []);
title("house02.tif");
axis off;
nexttile;
imshow(shiftedLg, []);
title("lena\_gray\_512.tif");
axis off;
nexttile;
imshow(shiftedLs, []);
title("lunar\_surface.tif");
axis off;
nexttile;
imshow(shiftedC, []);
title("characters\_test\_pattern.tif");
colormap gray;
axis off;

%% dft2D
function F = dft2D(f)
[m,n] = size(f);
F = zeros(m,n);
for i=1:m
    F(i,:) = fft(f(i,:));
end
for j=1:n
    F(:,j) = fft(F(:,j));
end
end
